/**
 * 公用方法
 */

import { parse } from 'querystring';
import { Order } from './queryHelper';
export const getPageQuery = () => parse(window.location.href.split('?')[1]);

// 登录结果 callback 处理，返回数据分类存储于 localStorage,设置菜单权限
export function setUserInfo(info) {
  localStorage.setItem('userInfo', JSON.stringify(info));
  if (info.permissions && info.permissions.permissions) {
    const permissions = info.permissions.permissions;
    const clonenAuthority = [];
    permissions.map((auth) => {
      if (auth.displayName) {
        clonenAuthority.push(auth.displayName);
      }
    });
  }
}

// 获取 localStorage 里面的用户信息
export function getUserInfo() {
  const userinfo = localStorage.getItem('userInfo');
  if (userinfo && userinfo !== 'undefined' && userinfo !== '') {
    return JSON.parse(userinfo);
  }
  return null;
}

// 清除缓存
export const clearLocalStorage = () => {
  localStorage.removeItem('userInfo');
  localStorage.removeItem('x-okapi-token');
  localStorage.removeItem('allDictionary');
  sessionStorage.removeItem('isLogin');
  sessionStorage.removeItem('flag');
  sessionStorage.removeItem('chooseAppInfo');
  sessionStorage.removeItem('curRoleDetail');
};

// 菜单权限控制处理
export const menuDataList = (menuList, formatMessage) => {
  const permissions = getUserInfo()?.permissions.permissions;
  const filterUndefined = (item) => typeof item !== 'undefined';
  return menuList
    .map((item) => {
      if (permissions.includes(item.name)) {
        const localItem = {
          ...item,
          path: window.__POWERED_BY_QIANKUN__ ? 'settingsuser' + item.path : item.path,
          name: formatMessage({ id: `menu.${item.name}` }),
          children: item.children ? menuDataList(item.children, formatMessage) : undefined,
        };
        return localItem || null;
      }
    })
    .filter(filterUndefined);
};

/**
 * @param {string} permissonName
 * @returns {Boolean}
 */
export function ifPermission(permissonName) {
  const permsAll = getUserInfo()?.permissions.permissions || [];
  if (permsAll.includes(permissonName)) {
    return true;
  } else {
    return false;
  }
}

/**
 * 判断对象是否是空值
 * @return Boolean类型，是否是空值，包括 '',null,undefind
 */
export const isNull = (obj) => {
  if (obj == null || obj === '' || obj === undefined || obj === 'undefined') {
    return true;
  } else {
    return false;
  }
};

const loop = (data) => {
  data.forEach((item) => {
    if (item.children) {
      loop(item.children);
    }
    item.value = item.dicCode || '';
    item.label = item.dicName || item.label || '';
    item.key = item.id;
  });
  return data;
};

/**
 * @description 根据字典类型，获取字典项
 * @param {String} code  类型名称
 * @returns 格式如下: [{value:code,label:dName}]
 */
export const dict = (code) => {
  let _dicData = localStorage.getItem('allDictionary');
  let _dictArray = [];
  if (!isNull(_dicData)) {
    let _d = JSON.parse(_dicData);
    for (let i in _d) {
      if (_d[i].typeCode === code) {
        _dictArray.push(_d[i]);
        continue;
      }
    }
  }
  _dictArray = _dictArray.map((e) => {
    let children = null;
    if (e.children && e.children.length > 0) {
      children = loop(e.children);
    }
    return {
      label: e.dicName || e.label || '',
      value: e.dicCode || '',
      children,
      key: e.id,
      ...e,
    };
  });
  return _dictArray;
};

// 处理列表宽度
export const calcWidth = (columns = []) => {
  return columns.reduce((acc, item) => {
    return acc + (item.width || 0);
  }, 0);
};

// 处理列表序号
export function withRowNumber(list, currentPage = 1, pageSize = 1) {
  return list.map((item, index) => ({
    __ROW_NO__: (currentPage - 1) * pageSize + index + 1,
    ...item,
  }));
}

/**
 * @description 处理字段排序
 * @param {String} sorter  table列表动态排序参数
 * @param {String} col     默认排序字段名
 * @param {String} tName   排序字段名所要添加的表名前缀
 * @param {String} tField  需要添加表名前缀的字段
 * @returns 格式如下: [{fieldName:sorterBy,order:sorterType}]
 */
export function taskSorter(sorter, col, tName, tField) {
  const { field, order } = sorter;
  let sortBy = col,
    sortType = 'desc';
  if (!field) {
    sortBy = col;
    sortType = 'desc';
  } else if (!order) {
    sortBy = col;
    sortType = 'desc';
  } else {
    sortBy = field;
    sortType = order === 'ascend' ? 'asc' : 'desc';
  }

  // 动态添加需要添加表名的字段
  if (tField === sortBy) {
    return { fieldName: tName + '.' + sortBy, order: Order[sortType] };
  } else {
    return { fieldName: sortBy, order: Order[sortType] };
  }
}

// 字典表映射
export const mapDict = (arr, code) => {
  let str;
  arr.forEach((item) => {
    if (item.value === code) str = item.label;
  });
  return str;
};

// antd Tree组件父子级逻辑交互方法
export const findChildrenKeysByKey = (nodes, key) => {
  for (let node of nodes) {
    if (node.key === key) {
      const keys = [node.key];
      if (node.children) {
        for (let child of node.children) {
          keys.push(...findChildrenKeysByKey(node.children, child.key));
        }
      }
      return keys;
    } else if (node.children) {
      const keys = findChildrenKeysByKey(node.children, key);
      if (keys.length > 0) {
        return keys;
      }
    }
  }
  return [];
};

// antd Tree组件父子级逻辑交互方法
export const getAncestorKeys = (allData, treeData, targetKey, result = []) => {
  for (let i = 0; i < treeData.length; i++) {
    const node = treeData[i];
    if (node.children) {
      // 如果当前节点有子节点，则递归查找子节点
      if (node.children.some((child) => child.key == targetKey)) {
        // 如果子节点包含目标节点，则将当前节点的key添加到结果数组中
        result.push(node.key);
        getAncestorKeys(allData, allData, node.key, result);
      } else {
        getAncestorKeys(allData, node.children, targetKey, result);
      }
    }
  }
  return result;
};
